<template>
  <div
    v-show="show"
    class="Fg-notice"
    :style="{...newStyle,paddingRight:this.$attrs.closable ? `calc(${newStyle.paddingRight} + 40px)` : newStyle.paddingRight}"
  >
    <div class="Fg-notice--wrap" ref="noticeBox" :style="{'--time':time,}">
      <div class="Fg-notice--content" ref="notice">
        <i :class="$attrs.icon" style="margin-right: 8px;"></i>
        <span>{{modelValue}}</span>
      </div>
    </div>
    <div class="Fg-notice--close" v-if="$attrs.closable" @click="show=!show">
      <i class="el-icon-close"></i>
    </div>
  </div>
</template>

<script>
import { comMixin } from "../../../utils/comMixins";
export default {
  mixins: [comMixin],
  name: "form-notice",
  props: {
    modelValue: {
      type: [Number, String],
      default: "",
    },
    speed: {
      type: [Number, String],
      default: "",
    },
  },
  data() {
    return {
      time: "0s",
      show: true,
    };
  },

  watch: {
    modelValue() {
      this.getTime();
    },
    speed() {
      this.getTime();
    },
  },
  mounted() {
    this.getTime();
  },

  methods: {
    getTime() {
      // 确保DOM已经渲染完毕
      this.$nextTick(() => {
        const notice = this.$refs.notice;
        const noticeBox = this.$refs.noticeBox;
        if (notice) {
          // 获取div的宽度
          const width = notice.offsetWidth;
          const width2 = noticeBox.offsetWidth;
          if (width < width2 - 30) {
            this.time = "0s";
          } else {
            console.log("width", width);
            // 速率=speed
            this.time = width / this.speed + "s";
          }
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
/* 定义滚动动画 */
@keyframes scroll-text {
  0% {
    transform: translateX(0); /* 从容器右侧开始 */
  }
  100% {
    transform: translateX(-100%); /* 滚动到容器左侧 */
  }
}
.Fg-notice {
  padding: 0 16px;
  position: relative;
  font-size: 14px;
  height: 40px;
  // color: #ed6a0c;
}
.Fg-notice--wrap {
  height: 100%;
  // padding: 0 16px;
  // background-color: #fffbe8;
  overflow: hidden; /* 隐藏超出部分 */
  white-space: nowrap; /* 防止文字换行 */
  display: flex; /* 使用flex布局 */
  align-items: center; /* 垂直居中 */
}

.Fg-notice--content {
  display: inline-block; /* 使内容成为行内块元素 */
  // padding-left: 100%; /* 确保内容宽度足够滚动 */
  animation: scroll-text 10s linear infinite; /* 调整滚动速度和时间 */
  animation-duration: var(--time);
}
.Fg-notice--close {
  position: absolute;
  top: 0;
  bottom: 0;
  right: 16px;
  display: flex;
  align-items: center;
  cursor: pointer;
}
</style>